package com.campus.filter;

import com.campus.common.JwtUtil;
import io.jsonwebtoken.Claims;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;


public class JwtFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 从请求头中获取 Token
        String token = httpRequest.getHeader("token");

        if (token != null) {
            Claims claims = JwtUtil.validateToken(token);
            if (claims != null) {
                // 提取 roleId
                int roleId = claims.get("roleId", Integer.class);

                // 获取请求的 URI
                String requestURI = httpRequest.getRequestURI();
                System.out.println(requestURI);

                // 管理员可以访问所有 /api/ 路径
                if (roleId == 1) {
                    if (requestURI.startsWith("/homework")) {
                        // 允许管理员访问 /api/* 路径
                        httpRequest.setAttribute("username", claims.getSubject());
                        chain.doFilter(request, response);
                        return;
                    }
                }

                // 教师只能访问 /api/course 和 /api/unit 路径，也就是只能进行课程管理和学习单元管理
                if (roleId == 2) {
                    if (requestURI.startsWith("/homework/course") || requestURI.startsWith("/homework/unit")) {
                        // 允许教师访问路径
                        httpRequest.setAttribute("username", claims.getSubject());
                        chain.doFilter(request, response);
                        return;
                    }
                }

                // 如果角色不匹配访问的路径，返回 403 错误
                httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                httpResponse.getWriter().write("{\"error\": \"Forbidden: Insufficient privileges\"}");
                return;
            }
        }

        // 如果 Token 无效或不存在，返回 401 错误
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("{\"error\": \"Unauthorized\"}");
    }

    @Override
    public void destroy() { }
}
